package rtkacaster

import (
	"gitee.com/ymofen/golog"
	"gitee.com/ymofen/sputils"
	"sync"
)

type EphChannel struct {
	logger  golog.Logger
	subconf string
	sub     *sputils.SpBaseSub
}

var (
	ephLk      sync.RWMutex
	ephChannel *EphChannel
)

func CheckEphStart(subconf string) error {
	ephLk.RLock()
	if ephChannel != nil && ephChannel.subconf == subconf {
		ephLk.RUnlock()
		return nil
	}
	ephLk.RUnlock()

	ephLk.Lock()
	defer ephLk.Unlock()
	if ephChannel != nil {
		ephChannel.Close()
	}
	ephChannel = NewEphChannel(subconf)
	err := ephChannel.Open()
	if err != nil {
		ephChannel = nil
	}
	return err
}

func NewEphChannel(conf string) *EphChannel {
	eph := &EphChannel{subconf: conf}
	return eph
}

func (this *EphChannel) onInputNotifyFunc(id, topic string, args ...interface{}) (ok bool) {
	action := args[0].(int)
	if action == sputils.SpTypeConnected {
		this.logger.Infof("%s connected", id)
	} else if action == sputils.SpTypeConnectFail {
		this.logger.Infof("%s connect fail\terr=%v", id, args[2])
	} else if action == sputils.SpTypeData {
		buf := args[1].([]byte)
		err := RtkACasterPub(id, buf)
		if err != nil {
			this.logger.Warnf("pub fail")
		}
	}
	return true
}

func (this *EphChannel) Close() error {
	this.sub.Close()
	return nil
}

func (this *EphChannel) Open() error {
	ephId := "RTKEPH"
	this.logger = golog.Default().WithOptionEx(golog.WithOptionPrefix(ephId))
	CheckStartRtkACaster()
	this.logger.Infof("caster\taddr=%s", GetRtkACasterAddr())
	this.sub = sputils.NewSpBaseSub("ephinput")
	err := this.sub.ReloadConfString(this.subconf, func(id, topic string, args ...interface{}) (ok bool) {
		return this.onInputNotifyFunc(ephId, topic, args...)
	})
	if err != nil {
		this.logger.Error(err.Error())
	}
	return nil
}

func init() {

}
